package com.hxh.basic.project.controller;

import com.alibaba.fastjson.JSONObject;
import com.hxh.basic.project.utils.DingdingUtil;
import com.hxh.basic.project.utils.JwtTokenUtils;
import com.hxh.basic.project.utils.ResultVoUtil;
import com.hxh.basic.project.vo.ResultVo;
import com.taobao.api.ApiException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@CrossOrigin
@RestController
@RequestMapping("/oauth")
public class OauthController {

    @Resource
    private DingdingUtil dingDingUtil;

    /**
     *
     * @param code 钉钉授权认证码
     * @return
     */
    @RequestMapping("/dingLogin")
    public ResultVo dingLogin(@RequestParam("code") String code) throws ApiException {
        System.out.println(code);
        String accessToken = dingDingUtil.getDingDingAccessToken();
        JSONObject userInfo = dingDingUtil.getUserInfoByAccessToken(code,accessToken);
        if(null == userInfo){
            return ResultVoUtil.error("钉钉认证失败！");
        }
        String userId = userInfo.getJSONObject("result").getString("userid");
        JSONObject userDetail = dingDingUtil.getUserDetail(userId);//用户详细信息
        String dingUserId = userDetail.getString("userid");
        String userIdToken = JwtTokenUtils.createOauthToken(dingUserId);
        userDetail.put("token",userIdToken);
        return ResultVoUtil.success(userDetail);
    }

    @PostMapping("/getDingUserInfo")
    public ResultVo getDingUserInfo(@RequestParam("token") String token) throws ApiException {
        String dingUserId = JwtTokenUtils.getUsername(token);
        JSONObject userDetail = dingDingUtil.getUserDetail(dingUserId);//用户详细信息
        return ResultVoUtil.success(userDetail);
    }

    @PostMapping("/getDingUserByUserId")
    public ResultVo getDingUserByUserId(@RequestParam("userId") String userId) throws ApiException {
        JSONObject userDetail = dingDingUtil.getUserDetail(userId);//用户详细信息
        String userIdToken = JwtTokenUtils.createOauthToken(userDetail.getString("userid"));
        userDetail.put("token",userIdToken);
        return ResultVoUtil.success(userDetail);
    }
}
